package com.chushouya.manager.service.admin.impl;


import com.general.framework.core.exception.BusinessException;
import com.general.framework.core.schema.PageResult;
import com.chushouya.manager.dao.entity.AttachmentEntity;
import com.chushouya.manager.dao.repository.AttachmentRepository;
//=====manager.dto.admin.attachment.*;
import com.chushouya.manager.dto.admin.attachment.AttachmentListDTO;
import com.chushouya.manager.dto.admin.attachment.AttachmentQuery;
import com.chushouya.manager.dto.admin.oss.OssCallbackDTO;
import com.chushouya.manager.service.admin.AttachmentService;
import com.chushouya.manager.config.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;

/**
 * 附件服务实现
 */
@Slf4j
@Service
public class AttachmentServiceImpl implements AttachmentService {

    @Resource
    private AttachmentRepository attachmentRepository;
    
    @Resource
    private OssProperties ossProperties;

    @Override
    public PageResult<AttachmentListDTO> selectPage(AttachmentQuery query) {
        PageResult<AttachmentEntity> pageResult = attachmentRepository.selectPageResult(query);
        return PageResult.of(pageResult, AttachmentListDTO.class);
    }

    @Override
    public void remove(Long id) {
        AttachmentEntity entity = attachmentRepository.selectByPrimaryKey(id);
        if (Objects.isNull(entity)) {
            throw new BusinessException("附件不存在");
        }
        // 直接删除记录
        attachmentRepository.deleteByPrimaryKey(id);
    }

    @Override
    public void handleOssCallback(OssCallbackDTO callbackDTO) {
        try {
            log.info("开始处理OSS上传回调: {}", callbackDTO.getFilename());

            // 解析文件信息
            String decodedFilename = callbackDTO.getDecodedFilename();
            String actualFilename = callbackDTO.getActualFilename();
            String directoryPath = callbackDTO.getDirectoryPath();

            log.info("解析文件信息 - 完整路径: {}, 文件名: {}, 目录: {}", 
                decodedFilename, actualFilename, directoryPath);

            // 创建附件实体
            AttachmentEntity attachment = new AttachmentEntity();
            
            // 基本文件信息
            attachment.setAttachmentName(actualFilename);
            // 构建完整的访问URL：host + 文件路径
            String fullUrl = ossProperties.getHost() + "/" + decodedFilename;
            attachment.setFillUrl(fullUrl); // 完整地址
            attachment.setMimeType(callbackDTO.getMimeType()); // MIME类型
            attachment.setStatus(1); // 1-正常
            attachment.setCreateTime(new Date());
            attachment.setUpdateTime(new Date());
            attachment.setHandleUser("system"); // 处理用户，默认系统
            
            // 文件大小转换（字节转KB）
            Long sizeInBytes = callbackDTO.getSizeAsLong();
            if (sizeInBytes != null && sizeInBytes > 0) {
                BigDecimal sizeInKB = new BigDecimal(sizeInBytes).divide(new BigDecimal(1024), 2, BigDecimal.ROUND_HALF_UP);
                attachment.setFileSize(sizeInKB);
            }

            // 如果是图片文件，设置宽高信息
            if (callbackDTO.isImage()) {
                Integer width = callbackDTO.getWidthAsInteger();
                Integer height = callbackDTO.getHeightAsInteger();
                
                if (width != null && height != null) {
                    // 格式化为 "宽x高" 的字符串
                    attachment.setWidthHeight(width + "x" + height);
                }
                
                log.info("图片文件信息 - 尺寸: {}x{}, 格式: {}", width, height, callbackDTO.getFormat());
            }

            // 保存附件记录到数据库
            attachmentRepository.insert(attachment);
            
            log.info("OSS回调处理完成，附件记录已保存: attachmentId={}", attachment.getAttachmentId());

        } catch (Exception e) {
            log.error("处理OSS回调失败: {}", callbackDTO.getFilename(), e);
            throw new BusinessException("处理OSS回调失败: " + e.getMessage());
        }
    }
}
